<?php

declare(strict_types=1);

namespace app\controller\member;

use app\controller\admin\AdminBaseController;
use app\model\admin\SysMember as SysMemberModel;
use think\exception\HttpException;
use think\facade\Db;
use think\Request;
use app\model\admin\SysMemberMenu as SysMemberMenuModel;

class User extends AdminBaseController
{
    public function index(Request $request)
    {
        $field = "*";
        $data = SysMemberModel::scope('where', $request->param())
            ->where('parent_id', $request->create_by)
            ->field($field)
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        return successPage($data);
    }

    public function save(Request $request)
    {
        $this->checkPermit($request->create_by);

        $param = $request->param();
        if (isset($param['id'])) {
            unset($param['id']);
        }


        $param['parent_id'] = $request->create_by;

        $parent = Db::table('member_user')->where('id', $request->create_by)->find();
        $param['group_id'] = $parent['group_id'] ?? 0;
        if ($param['group_id'] == 0) {
            return error('分组参数有误');
        }
        $param['password'] = md5($param['password']);
        $data = SysMemberModel::create($param);
        $user_id = $data->id;
        return $user_id ? success([], "新增成功") : error('操作失败');
    }

    public function show(Request $request)
    {
        $id = $request->param('id', 0);

        $data = SysMemberModel::where('id', $id)->where('parent_id', $request->create_by)->find();

        return success([
            'user' => $data
        ]);
    }

    public function update(Request $request)
    {
        $this->checkPermit($request->create_by);

        $param = $request->except(['password', 'login_ip', 'login_time', 'create_by', 'group_id', 'parent_id']);
        $id = $param['id'];
        if (isset($param['id'])) {
            unset($param['id']);
        }


        $model = SysMemberModel::where('id', $id)->where('parent_id', $request->create_by)->find();

        $msg = 'success';

        $ret = $model->save($param);
        return $ret ? success([], "更新成功") : error($msg);
    }

    public function delete(Request $request)
    {
        $id = $request->param('id', '');
        if (!$id) {
            return error('缺少必要参数');
        }

        $ids = explode(',', $id);
        if (in_array(1, $ids)) {
            return error('包含不可删除数据');
        }

        $real_ids = DB::table('member_user')->whereIn('id', $ids)->where('parent_id', $request->create_by)->column('id');
        if (!$real_ids) {
            return error('无可删除数据');
        }

        $result = SysMemberModel::destroy($real_ids);

        return $result ? success([], "删除成功") : error('删除失败');
    }

    public function resetPwd(Request $request)
    {
        $id = $request->post('id');
        $password = $request->post('password');

        $user = SysMemberModel::where('id', $id)->where('parent_id', $request->create_by)->find();
        if (!$user) {
            return error('数据不存在');
        }
        $user->password = md5(trim($password));
        $user->save();

        return success([], '更新成功');
    }


    public function changeStatus(Request $request)
    {
        $id = $request->param('id');
        $status = $request->param('status', '');
        if (!$id || $status == '') {
            return error('缺少必要参数');
        }

        $model = SysMemberModel::where('id', $id)->where('parent_id', $request->create_by)->find();

        $data = $request->only(['status']);

        $ret = $model->save($data);
        if (!$ret) {
            return error('更新失败');
        }
        return success();
    }

    public function profile(Request $request)
    {
        $id = $request->create_by;
        $data = SysMemberModel::where('id', $id)->find();
        return success([
            'user' => $data,
        ]);
    }

    public function updateProfile(Request $request)
    {
        $id = $request->create_by;
        if (!$id) {
            return error('缺少必要参数');
        }

        $data = $request->only(['nickname', 'email', 'phone', 'sex']);
        $data['update_by'] = $id;
        $data['update_time'] = time();

        $ret = Db::table('member_user')->where('id', $id)->update($data);

        if (!$ret) {
            return error('更新失败');
        }
        return success();
    }

    public function updatePwd(Request $request)
    {
        $id = $request->create_by;
        if (!$id) {
            return error('缺少必要参数');
        }

        $param = $request->only(['oldPassword', 'newPassword']);
        $oldPassword = $param['oldPassword'];
        $newPassword = $param['newPassword'];
        if (!$oldPassword || !$newPassword) {
            return error('缺少必要参数');
        }
        $model = SysMemberModel::find($id);
        if ($model->password != md5($oldPassword)) {
            return error('旧密码不正确');
        }

        $data = [];
        $data['update_by'] = $id;
        $data['update_time'] = time();
        $data['password'] = md5($newPassword);

        $ret = Db::table('member_user')->where('id', $id)->update($data);

        if (!$ret) {
            return error('更新失败');
        }
        return success();
    }

    protected function checkPermit($user_id)
    {
        $user = Db::table('member_user')->where('id', $user_id)->find();
        if ($user['parent_id'] > 0) {
            throw new HttpException(200, '子账号禁止此操作');
        }
    }

    // 根据角色ID查询菜单下拉树结构
    public function userMenuTreeselect(Request $request)
    {
        $user_id = $request->param('user_id', 0);
        $data = SysMemberMenuModel::where('status', '1')->field('id,menu_name,parent_id,order_num')->select();
        $menus = makeTree($data->toArray(), 'id', 'parent_id');
        $checkedKeys = Db::table('member_user_menu')->where('user_id', $user_id)->column('menu_id');
        return success([
            'menus' => $menus,
            'checkedKeys' => $checkedKeys
        ]);
    }

    public function updateUserMenu(Request $request)
    {
        $user_id = $request->post('user_id', 0);
        $menuIds = $request->post('menuIds', []);
        if (count($menuIds) === 0) {
            return error('请分配菜单');
        }
        $user = Db::table('member_user')->where('id', $user_id)->where('parent_id', $request->create_by)->find();
        if (!$user) {
            return error('用户不存在');
        }

        $add_datas = [];
        Db::startTrans();
        try {
            Db::table('member_user_menu')->where('user_id', $user_id)->delete();
            foreach ($menuIds as $menu_id) {
                $add_datas[] = [
                    'menu_id' => $menu_id,
                    'user_id' => $user_id,
                ];
            }
            Db::table('member_user_menu')->insertAll($add_datas);
            // 提交事务
            Db::commit();
            $result = true;
        } catch (\Exception $e) {
            $result = false;
            $msg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $result ? success([], "更新成功") : error($msg);
    }
}
